/*Copyright 2009-2010 by Ward, David J ( pymethius@ominian.net )
Licensed work, all rights reserved.*/
/**
 *
 *
 *TODO - bad spot for this but remember http://www.schillmania.com/projects/soundmanager2/
 *
 */
Ext.namespace("wm");
Ext.namespace("wmlib");

    wmlib.router = function(){    
        var self = this;
        var callbacks = {};
        //TODO - Evaluate if this needs wrappers - addModule, hasModule, unloadModule|stabModule2Death
        self.modules = {};


        /*********************************/
        //Routing logic
        /*********************************/
        self.route = function(msg){
            try{
                if( msg.method !== undefined){
                    wmlog.info("Delegating ", msg, " to Router.route_request");
                    return route_request(msg);
                }
                
                if( msg.result !== undefined) {
                    wmlog.info("Delegating ", msg, " to Router.route_request");
                    return route_response(msg);
                }
                if( msg.error !== undefined){
                    wmlog.info("Delegating ", msg, " to Router.route_request");
                    //TODO - implement callbacks
                    return route_error(msg);
                }
            }catch(execErr){
                wmlog.error("Sub router bombed out", execErr);
                
            }

            wmlog.error("Unknown message: " + msg );            
            return false; //Seriously Shut the F%*K up JSLINT
        }
        
        var route_error = function(msg){
            wmlog.error("Server wasn't happy ", msg);
        }

        var route_request = function(msg){
            wmlog.log("Routing message ", msg);
            method = msg.method.split(".");        
            recipient = null;
            try{
                //TODO - This should very likely be a for loop, this seems semi-fragile right now
                switch(method.length){
                    case 1:
                        recipient = self.modules[method[0]];
                        break;
                    case 2:
                        recipient = self.modules[method[0]][method[1]];
                        break;
                    case 3:
                        recipient = self.modules[method[0]][method[1]][method[2]];
                        break;
                    default:
                        wmlog.error("Routing Failed");
                }                
            }catch(RouteErr){
                wmlog.error("Routing Error", "Missing loaded module: " + msg.method)                
                return;
            }

            try{
                wmlog.log("firing request to ", recipient);
                recipient(msg);
                return;
            }catch(processingError){
                wmlog.error("Request error", "Server request failed: " + msg.method);                
            }
            wmlog.error("route_request fell through");
        }

        var route_response = function(msg){
            if(msg.id != undefined){
                if(callbacks[msg.id] != undefined ){
                    callbacks[msg.id](msg);
                }
            }
        }

        /*********************************/
        //Helpers and handlers
        /*********************************/

        self.doWrite = function() { wmlog.error("IoC for Router.doWrite failed"); }

        self.makeId = function(){
            //A problem waiting to happen
            return "" + new Date().getTime() + '.' + Math.random() * 1000;
        }

        self.makeRequest = function(method, params, callback){
            var myId = self.makeId();
            if( callback != null ){
                callbacks[myId] = callback
            }
            wmlog.log("Router.makerequest ", method, params);
            self.doWrite( {"method":method, "params":params, id: myId} );
        }

        self.doResponse = function(result, id){
            wmlog.log("Router.doResponse for ID ", id, result);
            self.doWrite( {"result": result, "id": id});
        }

        self.doError = function(error, id){
            wmlog.log("Router.makerequest ", method, params);
            self.doWrite( {"error":error, "id":id } );
        }

        /*********************************/
        //END Routing logic
        /*********************************/
        var loaded = {};

        self.modules["loader"] = wm.loader.load;
        
        self.modules["alert"] = function(msg){
            if(msg.params instanceof Array){
                if(msg.params.length == 2) {
                    Ext.Msg.alert(msg.params[0], msg.params[1]);
                }else{
                    Ext.Msg.alert("Alert from server", msg.params[0]);
                }
            }else{
                Ext.Msg.alert("Alert from server", msg.params);
            }
        }
        
        
    }